package com.wt.test.webmvc.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Properties;

/**
 * @description
 * @author: wangtao
 * @date:10:37 2019/2/20
 * @email:taow02@jumei.com
 */
public class MyInitAware implements InitializingBean,ApplicationContextAware {

	private ApplicationContext applicationContext;

	public MyInitAware() {
		System.out.println("----MyInitAware----");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		DefaultListableBeanFactory factory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();

		for(String t:new String[]{"b1","b2"}){
			BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(BFactoryBean.class);
			bdb.getBeanDefinition().setAttribute("id", t);
			Properties props = new Properties();
			props.setProperty("propName", t);
			//设置BFactoryBean的属性值
			bdb.addPropertyValue("properties", props);
			bdb.addPropertyValue("interfaceClz", BInterface.class);
			//bean注册
			factory.registerBeanDefinition(toBeanName(t), bdb.getBeanDefinition());
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	private String toBeanName(String className) {
		try {
			int index = className.lastIndexOf(".") + 1;
			return className.substring(index, index + 1).toLowerCase() + className.substring(index + 1);
		} catch (Exception e) {
			return className;
		}
	}
}
